from django.utils.safestring import mark_safe
from django_filters.rest_framework import DjangoFilterBackend

from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework.filters import SearchFilter
from rest_framework.filters import OrderingFilter
from rest_framework import status

from XApiTestServer.models import ModuleInfo
from XApiTestServer.pagination import MyPageNumberPagination
from XApiTestServer.serializers import ModuleSerializer, ModuleSumSerializer
from XApiTestServer.utils.common import *
from XApiTestServer.utils.test_report import *
from XApiTestServer.utils.response import *


class ModuleViewSet(viewsets.ModelViewSet):
    queryset = ModuleInfo.objects.all()
    serializer_class = ModuleSerializer
    pagination_class = MyPageNumberPagination
    filter_backends = (OrderingFilter, SearchFilter, DjangoFilterBackend)
    search_fields = ('module_name',)
    filterset_fields = ('belong_project', )
    ordering_fields = ('update_time', )

    def nameValidator(self, project_id, modulename, module_id = None):
        if module_id:
            actualname = ModuleInfo.objects.filter(id=module_id).values('module_name')
            if actualname[0]['module_name'] == modulename:
                return False
            else:
                modulelist = ModuleInfo.objects.filter(belong_project=project_id).values('module_name')
                for a in modulelist:
                    if a['module_name'] == modulename:
                        return True
                    else:
                        continue
                return False
        else:
            modulelist = ModuleInfo.objects.filter(belong_project=project_id).values('module_name')
            for a in modulelist:
                if a['module_name'] == modulename:
                    return True
                else:
                    continue
            return False

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        response_body = SUCCESS_INFO
        response_body['data'] = serializer.data
        return Response(response_body)

    def create(self, request, *args, **kwargs):
        if request.data['module_name'] == '' or request.data['test_user'] == '' or request.data['belong_project'] == '':
            return Response(VERIFY_FIELDS_HINT, status=status.HTTP_201_CREATED)

        if self.nameValidator(request.data['belong_project'], request.data['module_name']):
            return Response(MODULE_EXISTS, status=status.HTTP_201_CREATED)

        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            response_body = SUCCESS_ADD
            response_body['data'] = serializer.data
            return Response(response_body, status=status.HTTP_201_CREATED, headers=headers)
        else:
            response_body = {'msg': '{msg}'.format(msg=serializer.errors)}
            return Response(response_body, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):

        if request.data['module_name'] == '' or request.data['test_user'] == '' or request.data['belong_project'] == '':
            return Response(VERIFY_FIELDS_HINT, status=status.HTTP_201_CREATED)

        if self.nameValidator(request.data['belong_project'], request.data['module_name'],request.data['id']):
            return Response(MODULE_EXISTS, status=status.HTTP_201_CREATED)

        serializer = self.get_serializer(data=request.data)
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        response_body = SUCCESS_UPDATE
        response_body['data'] = serializer.data
        return Response(response_body)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        response_body = SUCCESS_DEL
        return Response(response_body)


class ModuleSumViewSet(viewsets.ModelViewSet):

    queryset = ModuleInfo.objects.all()
    serializer_class = ModuleSumSerializer
    search_fields = ('module_name',)
    filterset_fields = ('belong_project', )
    ordering_fields = ('update_time',)

    def list(self, request, *args, **kwargs):
        belong_project = request.GET.get('belong_project', '')
        if belong_project:
            queryset = ModuleInfo.objects.filter(belong_project=belong_project)
        else:
            queryset = ModuleInfo.objects.all()

        serializer = self.get_serializer(queryset, many=True)

        response_body = SUCCESS_LIST
        response_body['results'] = serializer.data

        return Response(response_body)
